package com.pokermind.operator.service;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * SiliconFlow HTTP Client - 直接调用 OpenAI-compatible API
 *
 * @author PokerMind Team
 */
@Service
@ConditionalOnProperty(name = "pokermind.ai.siliconflow.enabled", havingValue = "true")
public class SiliconFlowHttpClient {

    private static final Logger logger = LoggerFactory.getLogger(SiliconFlowHttpClient.class);

    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    @Value("${pokermind.ai.siliconflow.api-key}")
    private String apiKey;

    @Value("${pokermind.ai.siliconflow.model:deepseek-ai/DeepSeek-V3}")
    private String model;

    @Value("${pokermind.ai.siliconflow.timeout:10000}")
    private int timeoutMs;

    public SiliconFlowHttpClient(
        @Value("${pokermind.ai.siliconflow.base-url:https://api.siliconflow.cn/v1}") String baseUrl) {
        this.webClient = WebClient.builder().baseUrl(baseUrl)
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();
        this.objectMapper = new ObjectMapper();

        logger.info("SiliconFlowHttpClient initialized - baseUrl: {}", baseUrl);
    }

    /**
     * 调用 SiliconFlow Chat Completion API
     */
    public String chatCompletion(String systemPrompt, String userPrompt) {
        try {
            ChatCompletionRequest request = new ChatCompletionRequest();
            request.model = model;
            request.maxTokens = 2000;
            request.temperature = 0.7;

            request.messages = new ArrayList<>();

            Message systemMsg = new Message();
            systemMsg.role = "system";
            systemMsg.content = systemPrompt;
            request.messages.add(systemMsg);

            Message userMsg = new Message();
            userMsg.role = "user";
            userMsg.content = userPrompt;
            request.messages.add(userMsg);

            logger.debug("SiliconFlow API Request - model: {}, timeout: {}ms", model, timeoutMs);
            logger.debug("Request body: {}", objectMapper.writeValueAsString(request));

            ChatCompletionResponse response =
                webClient.post().uri("/chat/completions").header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                    .bodyValue(request).retrieve()
                    .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                        clientResponse -> clientResponse.bodyToMono(String.class).flatMap(errorBody -> {
                            logger.error("SiliconFlow API Error Response: {}", errorBody);
                            return Mono.error(new RuntimeException("API Error: " + errorBody));
                        })).bodyToMono(ChatCompletionResponse.class).timeout(Duration.ofMillis(timeoutMs)).block();

            if (response != null && response.choices != null && !response.choices.isEmpty()) {
                String content = response.choices.get(0).message.content;
                logger.debug("SiliconFlow API Success - model: {}, tokens: {}", model,
                    response.usage != null ? response.usage.totalTokens : "unknown");
                logger.debug("SiliconFlow API Response Content: {}", content);
                return content;
            }

            logger.warn("SiliconFlow API returned empty response");
            return null;

        } catch (Exception e) {
            logger.error("SiliconFlow API call failed: {}", e.getMessage(), e);
            throw new RuntimeException("SiliconFlow API call failed", e);
        }
    }

    // ========== Request/Response DTOs ==========

    public static class ChatCompletionRequest {
        public String model;
        public List<Message> messages;

        @JsonProperty("max_tokens")
        public Integer maxTokens;

        public Double temperature;
    }

    public static class Message {
        public String role;
        public String content;
    }

    public static class ChatCompletionResponse {
        public String id;
        public String object;
        public Long created;
        public String model;
        public List<Choice> choices;
        public Usage usage;
    }

    public static class Choice {
        public Integer index;
        public Message message;

        @JsonProperty("finish_reason")
        public String finishReason;
    }

    public static class Usage {
        @JsonProperty("prompt_tokens")
        public Integer promptTokens;

        @JsonProperty("completion_tokens")
        public Integer completionTokens;

        @JsonProperty("total_tokens")
        public Integer totalTokens;
    }
}

